<script setup>
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(95, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);



//目标：创建5个颜色位置大小都是随机的立方体
//多個立方體自動旋轉,存儲cube
let cubeArr = []

function createCube () {
  // 1、数据
  let list = []
  for (let i = 0; i < 5; i++) {
    list.push({
      col: `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`,
      width: Math.floor(Math.random() * (3 - 1 + 1) + 1),
      height: Math.floor(Math.random() * (3 - 1 + 1) + 1),
      deep: Math.floor(Math.random() * (3 - 1 + 1) + 1),
      x: Math.floor(Math.random() * (5 - 1 + 1) + -5),
      y: Math.floor(Math.random() * (5 - 1 + 1) + -5),
      z: Math.floor(Math.random() * (5 - 1 + 1) + -5),
    })
  }

  //2、创建物体
  list.forEach(({ col, width, height, deep, x, y, z }) => {
    const geometry = new THREE.BoxGeometry(width, height, deep);
    const material = new THREE.MeshBasicMaterial({ color: col });
    const cube = new THREE.Mesh(geometry, material);
    cube.position.set(x, y, z)
    scene.add(cube);

    cubeArr.push(cube)
  })
}




//创建一个坐标轴
function createAxes () {
  //参数：坐标轴长度
  const axesHelper = new THREE.AxesHelper(5)
  //坐标轴也是一个物体需要加入到场景中使用(特殊)
  //物体虽然试几何图形+材质皮肤决定，坐标轴构造函数里决定好线段图形和颜色
  scene.add(axesHelper)
}


//创建轨道控制器
//轨道控制器（控制摄像机位置 ）
let controls
function createOrbit () {
  controls = new OrbitControls(camera, renderer.domElement)
  controls.update()
}
function animate () {
  requestAnimationFrame(animate)
  controls.update();
  //自动旋转
  cubeArr.forEach(cube => {
    cube.rotation.x += 0.1
    cube.rotation.y += 0.1
    cube.rotation.z += 0.1
  })
  renderer.render(scene, camera)
}







//适配画布大小
function resize () {
  window.addEventListener('resize', () => {
    renderer.setSize(window.innerWidth, window.innerHeight)
    //重新根据响应改变物体的宽高比
    camera.aspect = window.innerWidth / window.innerHeight
    //更新摄像机矩阵空间(让摄像机重新计算每个像素点位置和大小)
    camera.updateProjectionMatrix()
  })
}

//调用创建坐标轴
createAxes()

createOrbit()
resize()
createCube()
animate()
renderer.render(scene, camera)


</script>

<template></template>

<style scoped>
</style>
